package tjs.study.notes.eureka.clienta.user.service.feign.exception;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: tjs-spcloud
 * @desc: 直接抛出异常
 * @author: tjs
 * @create: 2019-10-06 01:19
 */
@Configuration
public class ThrowErrException implements ErrorDecoder {
    private static final Logger logger = LoggerFactory.getLogger(ThrowErrException.class);

    @Override
    public Exception decode(String methodKey, Response response) {

        Exception exception = null;
        try {
            // 获取原始的返回内容，可以转换成自定义的错误对象
            String json = Util.toString(response.body().asReader());
            Map resMap = JSON.parseObject(json, HashMap.class);
            //根据错误内容判断
            // 是否保留原来的错误信息
            exception = new RuntimeException(json);

            // 还是抛出自定义异常

            // 还是抛出HystrixBadRequestException异常，这个异常不会被fallback捕获，fixme 也就是不会作为熔断的判断标准
            //exception = new HystrixBadRequestException(resMap.get("message").toString());
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
        return exception;
    }


}
